package com.py.credit.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.py.credit.common.ServiceException;
import com.py.credit.dao.DatabaseDao;
import com.py.credit.dao.ModelBaseDao;
import com.py.credit.entity.Database;
import com.py.credit.entity.IndexCatModel;
import com.py.credit.entity.Model;
import com.py.credit.service.IndexService;
import com.py.credit.service.ModelBaseService;
import com.py.credit.utils.SQLBuilder;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.common.Page;

@Service
public class ModelBaseServiceImpl implements ModelBaseService {

	@Autowired
	private ModelBaseDao modelBaseDao;
	@Autowired
	private IndexService indexService;
	@Autowired
	private DatabaseDao databaseDao;

	@Override
	public List<Model> getListForPage(String sortType, Page page) {

		return modelBaseDao.getListForPage(sortType, page);
	}

	@Override
	public List<Map<String, Object>> getByConditionForPage(List<String> columns, String[] additionalColumns,
			String conditionStr, Page page, String kId, String areaId, String industryId) {
		List<String> conditions = SQLBuilder.createConditionSql(conditionStr);
		List<Map<String, Object>> batchLogs = modelBaseDao.selectByConditionForPage(columns, additionalColumns,
				conditions, page, kId, areaId, industryId);

		return batchLogs;
	}

	@Override
	public Integer getQueryCountByType(int type) {

		return modelBaseDao.selectQueryCountByType(type);
	}

	@Override
	@Transactional
	public String saveOrUpdate(String id, String bm, String name, String des, String scoreType, double rate,
			String zone, String industry, String reportType, String mainType, String relatedModel, String cjr) {
		if (id == null || id.equals("")) {
			id = UuidUtil.getUUid();
			modelBaseDao.insert(id, bm, name, des, scoreType, rate, zone, industry, reportType, mainType, relatedModel);
			if (StringUtils.isNotBlank(relatedModel)) {
				long currentTime = new Date().getTime();
				String currentTimeStr = String.valueOf(currentTime);
				modelBaseDao.copyIndexCategoryModel(relatedModel, id, "_" + currentTimeStr + "_" + cjr, cjr);
				modelBaseDao.copyIndexCategory(relatedModel, id, "_" + currentTimeStr + "_" + cjr, cjr);
				modelBaseDao.copyCategory(relatedModel, id, "_" + currentTimeStr + "_" + cjr, cjr);
				modelBaseDao.copyModelRank(relatedModel, id, "_" + currentTimeStr + "_" + cjr, cjr);
				modelBaseDao.copyModelRule(relatedModel, id, "_" + currentTimeStr + "_" + cjr, cjr);
			}
		} else {
			// id=UuidUtil.getUUid();
			modelBaseDao.update(id, bm, name, des, scoreType, rate, zone, industry, reportType, mainType, relatedModel);
		}
		return id;
	}

	@Override
	public List getRankList(String id) {
		// TODO Auto-generated method stub
		return modelBaseDao.getRankList(id);
	}

	@Transactional
	@Override
	public void modelIndexCatTreeSave(List<Map> listTree, String modelId, String userId) {
		// modelBaseDao.deleteTreeBefore(modelId);
		modelBaseDao.deleteTreeBefore1(modelId);
		modelBaseDao.deleteTreeBefore2(modelId);
		modelBaseDao.deleteTreeBefore3(modelId);
		List indexTree = new ArrayList<>();
		List categoryTree = new ArrayList<>();
		if (listTree != null && listTree.size() > 0) {
			for (int i = 0; i < listTree.size(); i++) {
				if (listTree.get(i) != null) {
					if (null != listTree.get(i).get("type") && "index".equals(listTree.get(i).get("type"))) {
						if (StringUtils.isBlank(String
								.valueOf(listTree.get(i).get("extra") == null ? "" : listTree.get(i).get("extra")))) {
							listTree.get(i).put("extra", "");
						}
						listTree.get(i).put("level",
								Integer.parseInt(String.valueOf(listTree.get(i).get("level"))) - 1);
						String idM = String.valueOf(listTree.get(i).get("indexCatModelId") == null ? ""
								: listTree.get(i).get("indexCatModelId"));
						if (StringUtil.isBlank(idM)) {
							idM = UuidUtil.getUUid();
						}
						listTree.get(i).put("idM", idM);
						indexTree.add(listTree.get(i));
					} else if (null != listTree.get(i).get("type") && "category".equals(listTree.get(i).get("type"))) {
						if (StringUtils.isBlank(String
								.valueOf(listTree.get(i).get("extra") == null ? "" : listTree.get(i).get("extra")))) {
							listTree.get(i).put("extra", "");
						}
						listTree.get(i).put("level",
								Integer.parseInt(String.valueOf(listTree.get(i).get("level"))) - 1);
						String idM = String.valueOf(listTree.get(i).get("indexCatModelId") == null ? ""
								: listTree.get(i).get("indexCatModelId"));
						if (StringUtil.isBlank(idM)) {
							idM = UuidUtil.getUUid();
						}
						listTree.get(i).put("idM", idM);
						categoryTree.add(listTree.get(i));
					} else {
						break;
					}
				}
			}
		}
		if (indexTree != null && indexTree.size() > 0) {
			modelBaseDao.saveIndexs(indexTree, modelId, userId);
		}
		if (categoryTree != null && categoryTree.size() > 0) {
			modelBaseDao.saveCategorys(categoryTree, modelId, userId);
		}
		if (listTree != null && listTree.size() > 0) {
			String scoreType = String.valueOf(modelBaseDao.selectOne(modelId).get("scoreType"));
			double weight = 0;
			if ("2".equals(scoreType)) {
				weight = 100;
			} else {
				weight = 0;
			}
			modelBaseDao.modelIndexCatTreeSave(listTree, modelId, weight, userId);
			for (int i = 0; i < listTree.size(); i++) {
				if (listTree.get(i).get("type").equals("index")) {
					indexService.editStatusById((String) listTree.get(i).get("indexOrCatId"));
				}
			}
			modelBaseDao.updateStep("3", modelId);
		}
	}

	@Override
	public List<Map> getAllCatAndIndexes(String mainType) {
		// TODO Auto-generated method stub
		return modelBaseDao.getAllCatAndIndexes(mainType);
	}

	@Override
	public List<Map> getRelatedCategoryAndIndexes(String catId) {
		// TODO Auto-generated method stub
		return modelBaseDao.getRelatedCategoryAndIndexes(catId);
	}

	@Override
	public List<Map> getRelatedCategoryAndIndexesByModelId(String modelId) {
		// TODO Auto-generated method stub
		return modelBaseDao.getRelatedCategoryAndIndexesByModelId(modelId);
	}

	@Override
	@Transactional
	public void updateWeight(List<IndexCatModel> list, String modelId) {
		if (list != null && list.size() > 0) {
			modelBaseDao.updateWeight(list);
			modelBaseDao.updateStep("4", modelId);
		}

		// modelBaseDao.updateWeight(list);

	}

	@Override
	public List<Map> getRuleListByIndexModelCat(String indexCatModelId) {
		// TODO Auto-generated method stub
		return modelBaseDao.getRuleListByIndexModelCat(indexCatModelId);
	}
	
	@Override
	public List<Map> getRuleListByIndexModelCatForZz(String indexCatModelId,String zzType) {
		// TODO Auto-generated method stub
		return modelBaseDao.getRuleListByIndexModelCatForZz(indexCatModelId,zzType);
	}

	@Override
	public void del(String ids) {
		// TODO Auto-generated method stub
		String[] idsArray = ids.split(",");
		modelBaseDao.del(idsArray);
	}

	@Override
	public void setStatus(String status, String id) {
		if (StringUtils.isNotBlank(id)) {
			if ("0".equals(status)) {
				status = "1";
			} else {
				if(this.getProcessCount(id)>0){
					throw new RuntimeException("该模型下已有流程在使用，无法停用！");
				}else if(this.getOrgModelCount(id)>0){
					throw new RuntimeException("有机构绑定该模型，请先解除绑定！");
				}
				status = "0";
			}
		} else {
			status = "1";
		}
		modelBaseDao.setStatus(status, id);

	}

	@Override
	public List<Map> getRelatedCategoryAndIndexesTreeByModelId(String modelId) {
		// TODO Auto-generated method stub
		return modelBaseDao.getRelatedCategoryAndIndexesTreeByModelId(modelId);
	}

	@Override
	public List<Map> getdefaultTree(String modelId) {
		// TODO Auto-generated method stub
		return modelBaseDao.getdefaultTree(modelId);
	}

	@Override
	public void updateStandard(String indexCatModelId, String standard) {
		modelBaseDao.updateStandard(indexCatModelId, standard);

	}

	@Override
	public void saveRules(List<Map> list, String indexCatModelId) {
		modelBaseDao.deleteRules(indexCatModelId);
		String modelId = modelBaseDao.selectModelIdByIndexCatModeId(indexCatModelId);
		if(list!=null&&list.size()>0){
			modelBaseDao.saveRules(list, indexCatModelId, modelId);
		}
	}

	@Transactional
	@Override
	public void saveRanks(List<Map> list, String id, String cjr) {
		modelBaseDao.deleteRanks(id);
		modelBaseDao.saveRanks(list, id, cjr);

	}

	@Override
	public Map selectOne(String id) {
		Map m = modelBaseDao.selectOne(id);
		if (m != null) {
			return m;
		}
		return null;
	}

	@Override
	public int validateBm(String id, String bm) {
		// TODO Auto-generated method stub
		return modelBaseDao.validateBm(id, bm);
	}

	@Override
	public int validateModel(String id, String zone, String industry, String reportType, String mainType) {
		// TODO Auto-generated method stub
		return modelBaseDao.validateModel(id, zone, industry, reportType, mainType);
	}

	@Override
	public List<Map> getRuleListByDict(String dictSource) {
		// TODO Auto-generated method stub
		return modelBaseDao.getRuleListByDict(dictSource);
	}

	@Override
	public int validateSetStatus(String id) {
		// TODO Auto-generated method stub
		return modelBaseDao.validateSetStatus(id);
	}

	@Override
	@Transactional
	public void updateProcess(String id, String templateType, String checkType, String checkProcess) {
		// TODO Auto-generated method stub
		if("1".equals(checkType)){
			checkProcess="";
		}
		modelBaseDao.updateProcess(id, templateType, checkType, checkProcess);
		modelBaseDao.updateStep("5", id);
	}

	@Override
	public List<Map> selectModelForSelect(String mainType) {
		// TODO Auto-generated method stub
		return modelBaseDao.selectModelForSelect(mainType);
	}

	@Override
	public List<Map<String, Object>> getModelListForPage(String name, Page page, String orgId) {

		return modelBaseDao.selectAllModelList(name, page, orgId);
	}

	@Override
	public List<Map<String, Object>> getModelList(String name) {

		return modelBaseDao.selectModelList(name);
	}

	@Override
	public List<Map<String, Object>> getModelListByConditionForPage(String orgId, List<String> showColumns,
			String[] additionalColumns, Page page, String condition, String kId, String areaId, String industryId) {

		if (CollectionUtils.isEmpty(showColumns)) {

			throw new ServiceException("至少选择一列");

		}
		List<String> conditions = SQLBuilder.createConditionSql(condition);

		return modelBaseDao.selectModelListByConditionForPage(orgId, areaId, kId, industryId, showColumns,
				additionalColumns, page, conditions);
	}

	@Override
	public Map<String, String> selectCheckProcessForOrg(String orgId, String id) {
		Map<String, String> m = modelBaseDao.selectCheckProcessForOrg(orgId, id);
		if (m == null) {
			m = modelBaseDao.selectOne(id);
		} else if (StringUtils.isBlank(m.get("checkType")) && StringUtils.isBlank(m.get("templateType"))
				&& StringUtils.isBlank(m.get("checkProcess"))) {
			m = modelBaseDao.selectOne(id);
		}
		return m;
	}

	@Override
	public List<Database> getDbList(String kId) {

		return databaseDao.selectList(kId);
	}

	@Override
	public void saveCheckProcessForOrg(String orgId, String id, String checkType, String checkProcess,
			String templateType) {
		modelBaseDao.saveCheckProcessForOrg(orgId, id, checkType, checkProcess, templateType);

	}

	@Override
	public int getProcessCount(String id) {
		// TODO Auto-generated method stub
		return modelBaseDao.getProcessCount(id);
	}

	@Override
	public int getOrgModelCount(String id) {
		// TODO Auto-generated method stub
		return modelBaseDao.getOrgModelCount(id);
	}

	@Override
	public List<Map> selectTemplateMap() {
		// TODO Auto-generated method stub
		return modelBaseDao.selectTemplateMap();
	}

	@Override
	public String selectMXSQ(String id) {
		return modelBaseDao.selectMXSQ(id);
	}

}
